package br.uniriotec.ppgi.leo.controller.nlp.wordnet;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import edu.mit.jwi.Dictionary;
import edu.mit.jwi.IDictionary;
import edu.mit.jwi.item.IIndexWord;
import edu.mit.jwi.item.ILexFile;
import edu.mit.jwi.item.ISynset;
import edu.mit.jwi.item.IWord;
import edu.mit.jwi.item.IWordID;
import edu.mit.jwi.item.POS;
import edu.mit.jwi.morph.WordnetStemmer;

public class MITWordnetUtils{

	/**
	 * Retrieves the first possible stem of a word.
	 * 
	 * @param word
	 * @param pos
	 * @return
	 * @throws IOException
	 */
	public static String stemWord(String word, POS pos) throws IOException{
		WordnetStemmer stemmer = new WordnetStemmer(dicitionaryFactory());
		return stemmer.findStems(word, pos).get(0);
	}
	
	
	
	
	
	
	public static void getSense(String word, POS pos, int senseInnerID) throws IOException {
		IDictionary dict = dicitionaryFactory();
		// look up first sense of the word "dog"
		IIndexWord idxWord = dict.getIndexWord(word, pos); 
		IWordID wordID = idxWord.getWordIDs().get(senseInnerID);
		IWord wnWord = dict.getWord(wordID);
		System.out.println("Id = " + wordID); 
		System.out.println("Lemma = " + wnWord.getLemma()); 
		System.out.println("Gloss = " + wnWord.getSynset().getGloss());
	}
	
	
	public static void getLemma(String word, POS pos) throws IOException{
		IDictionary dict = dicitionaryFactory();
		IIndexWord idxWord = dict.getIndexWord(word, pos); 
		IWordID wordID = idxWord.getWordIDs().get(0);
		IWord wnWord = dict.getWord(wordID);
		System.out.println(wnWord.getLemma());
	}
	
	
	
	
	public static ILexFile getSupersense(String word, POS pos, int senseId, IDictionary dict){
		System.out.println("Iniciando Processamento de Supersense para: '"+word+"'...");
		IIndexWord idxWord = dict.getIndexWord (word, pos);
        IWordID wordID = idxWord.getWordIDs().get(senseId) ;
        IWord wordObject = dict.getWord (wordID);   
        ISynset synset = wordObject.getSynset();
        return synset.getLexicalFile();
	}
	
	
	
	
	
	
	
	public static IWord getSenseById(String word, POS pos, String senseGeneralID) throws IOException{
		IDictionary dict = dicitionaryFactory();
		IIndexWord idxWord = dict.getIndexWord(word, pos); 
		IWord wnWord = null;
		for(IWordID wordID : idxWord.getWordIDs()){
			String id = wordID.toString().substring(4,12);
			if(id.equals(senseGeneralID)){
				wnWord = dict.getWord(wordID);
				break;
			}
		}
		return wnWord;
	}
	
	
	private static IDictionary dicitionaryFactory() throws IOException{
		System.out.println("Instanciando Dicionario...");
		// construct the URL to the Wordnet dictionary directory
		String wnhome = System.getenv("WNHOME");
		String path = wnhome + File.separator + "dict"; 
		URL url = new URL("file", null, path);
		// construct the dictionary object and open it
		IDictionary dict = new Dictionary(url); 
		dict.open();
		return dict;
	}

}
